//
//  addressViewController.m
//  lmq
//
//  Created by 千翼网络科技 on 2017/1/24.
//  Copyright © 2017年 yuanxin. All rights reserved.
//

#import "addressViewController.h"
#import "addaddressViewController.h"
#import "addressTableViewCell.h"
#import "MJRefresh.h"
#import "configddd.h"
#import <Masonry/Masonry.h>

@interface addressViewController ()

@end

@implementation addressViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [self requestData];
    //下拉刷新
    addressTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self requestData];
        [addressTableView.mj_header endRefreshing];
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setTitle:@"收货地址"];
    self.view.backgroundColor=[ZJCModel colorWithString:@"f2f2f2"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusNotification:) name:@"status" object:nil];
    [self requestData];
    
    UIButton *rightButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, screenScale(60), screenScale(30))];
    [rightButton addTarget:self action:@selector(rightNavItemClick) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setTitle:@"保存" forState:UIControlStateNormal];
    rightButton.titleLabel.font = get4sFont(14);
    UIBarButtonItem *rightBarButton=[[UIBarButtonItem alloc]initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem=rightBarButton;
    
    UIImageView *addressImageView=[[UIImageView alloc]initWithFrame:CGRectMake((DEF_SCREEN_WIDTH-(60))/2, (80), (60), (60))];
    addressImageView.image=[UIImage imageNamed:@"addressdatu"];
    [self.view addSubview:addressImageView];
    
    UILabel *addresslabel=[[UILabel alloc]initWithFrame:CGRectMake((DEF_SCREEN_WIDTH-(120))/2, (150), (120), (20))];
    addresslabel.text=@"收货地址为空";
    addresslabel.textAlignment=NSTextAlignmentCenter;
    [self.view addSubview:addresslabel];
    
//    xzButton=[[UIButton alloc]init];
//    xzButton.backgroundColor=[ZJCModel colorWithString:@"222222"];
//    [xzButton addTarget:self action:@selector(xzButtonClick) forControlEvents:UIControlEventTouchUpInside];
//    [xzButton setTitle:@"新增地址" forState:UIControlStateNormal];
//    xzButton.titleLabel.font = get4sFont(14);
//    [self.view addSubview:xzButton];
//    [xzButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.mas_equalTo(self.view).with.offset(0);
//        make.left.mas_equalTo(self.view).with.offset(0);
//        make.width.mas_equalTo(scrWidth());
//        make.left.mas_equalTo(screenScale(80));
//    }];
    
    addressTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64-screenScale(80)) style:UITableViewStylePlain];
    addressTableView.delegate=self;
    addressTableView.dataSource=self;
    addressTableView.backgroundColor=[ZJCModel colorWithString:@"f2f2f2"];
    addressTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:addressTableView];
    
    
    UIButton *addButton=[[UIButton alloc]init];
    addButton.backgroundColor=[UIColor blackColor];
    [addButton setTitle:@"新增地址" forState: UIControlStateNormal];
    addButton.titleLabel.font = get4sFont(14);
    [addButton addTarget:self action:@selector(addButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addButton];
    [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).with.offset(0);
        make.left.mas_equalTo(self.view).with.offset(0);
        make.width.mas_equalTo(scrWidth());
        make.height.mas_equalTo(screenScale(80));
    }];
}

#pragma mark - statusNotification

- (void)statusNotification:(NSNotification *)text{

//    更改默认收货地址
    
    if ([text.userInfo[@"selected"]isEqualToString:@"yes"]) {
        
        for (int i = 0; i < dataArr.count ; i ++) {
            
            [dataArr[i] setValue:@"0" forKey:@"status"];
            if (i == [text.userInfo[@"status"] intValue]) {
                
                [dataArr[i] setValue:@"1" forKey:@"status"];
            }
        }
        NSLog(@"===data=====%@",dataArr);
        [addressTableView reloadData];
    }
    
//    删除收货地址
    
    if ([text.userInfo[@"delete"] isEqualToString:@"yes"]) {
        
        for (int i = 0; i < dataArr.count ; i ++) {
            
            if (i == [text.userInfo[@"status"] intValue]) {
                
                if ([[dataArr[i] objectForKey:@"status"] intValue] == 1) {
                    
                    [PublicFunction showAlert:nil message:@"默认收货地址" duration:5.0f];
                }else{
                
                    NSString *uidStr=[PublicFunction getConfigWithKey:@"uid"];
                    NSString *tokenStr=[PublicFunction getConfigWithKey:@"token"];
                    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
                    [productParams setValue:uidStr forKey:@"member_id"];
                    [productParams setValue:tokenStr forKey:@"token"];
                    [productParams setValue:[dataArr[i] objectForKey:@"id"] forKey:@"id"];
                    
                    [[MNetworkHandler sharedInstance]conURL:Delete_Address
                                                networkType:NetWorkPOST
                                                     params:productParams
                                                   delegate:nil
                                                    showHUD:NO
                                               successBlock:^(id returnData) {
                                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                                       
                                                       NSLog(@"success===========%@",returnData);
                                                       
                                                       [self requestData];
                                                       
                                                   }
                                                   else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                                       
                                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                                       
                                                   }
                                               } failureBlock:^(NSError *error) {
                                                   NSLog(@"%@",error);
                                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                                               }];
                }
            }
        }
    }
}

#pragma mark - requestData

- (void)requestData{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSString *uidStr=[PublicFunction getConfigWithKey:@"uid"];
    NSString *tokenStr=[PublicFunction getConfigWithKey:@"token"];
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue:uidStr forKey:@"member_id"];
    [productParams setValue:tokenStr forKey:@"token"];
    
    [[MNetworkHandler sharedInstance]conURL:Address
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       NSLog(@"address===========%@",returnData);
                                       
                                       dataArr = [[NSMutableArray alloc]init];
                                       dataArr = [returnData objectForKey:@"data"];
                                       
                                       [addressTableView reloadData];
                                       
                                       [hud removeFromSuperview];
                                   }
                                   else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                       
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       
                                   }
                               } failureBlock:^(NSError *error) {
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
}

-(void)addButtonClick{
    NSLog(@"新增地址");
    addaddressViewController*addaddressVC=[[addaddressViewController alloc]init];
    
    if (dataArr.count == 0) {
        
        addaddressVC.mark = @"yes";
    }else{
        
        addaddressVC.mark = @"no";
    }
    
    [self.navigationController pushViewController:addaddressVC animated:YES];
}

//-(void)xzButtonClick{
//    NSLog(@"新增地址");
//    addaddressViewController*addaddressVC=[[addaddressViewController alloc]init];
//    [self.navigationController pushViewController:addaddressVC animated:YES];
//}

#pragma mark - 点击右导航
-(void)rightNavItemClick{
    NSLog(@"保存");
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSString *str;
    
    for (int i = 0 ; i < dataArr.count ; i ++) {
        
        if ([[NSString stringWithFormat:@"%@",[dataArr[i] objectForKey:@"status"] ]isEqualToString:@"1"]) {
            str = [NSString stringWithFormat:@"%@",[dataArr[i] objectForKey:@"id"]];
            break;
        }
    }
    NSLog(@"=====%@",str);
    
    NSString *uidStr=[PublicFunction getConfigWithKey:@"uid"];
    NSString *tokenStr=[PublicFunction getConfigWithKey:@"token"];
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue:uidStr forKey:@"member_id"];
    [productParams setValue:tokenStr forKey:@"token"];
    [productParams setValue:str forKey:@"id"];
    
    [[MNetworkHandler sharedInstance]conURL:Default_Address
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       //[PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       [hud removeFromSuperview];
                                       NSLog(@"address===========%@",returnData);
                                       
                                   }
                                   else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                       
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       
                                   }
                               } failureBlock:^(NSError *error) {
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
}

#pragma mark -----UITableViewDataSource-----

//返回分区数(默认为1)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//返回每一行的cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataArr.count;
}

#pragma mark -----UITableViewDelegate-----

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    addressId = [dataArr[indexPath.row][@"id"] intValue];
    
    NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"yes",@"selected",[NSString stringWithFormat:@"%d",addressId],@"addressId",dataArr[indexPath.row],@"address", nil];
    NSNotification *notification =[NSNotification notificationWithName:@"address_Id" object:nil userInfo:dict];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    
    [self.navigationController popViewControllerAnimated:YES];
}

//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return screenScale(200);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    addressTableViewCell *cell=(addressTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"addressTableViewCell"];
    if (cell == nil) {
        cell=[[addressTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"addressTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
        cell.addressViewController=self;//控制器传给cell
    
    cell.dataDic = dataArr[indexPath.row];
    cell.indexPath = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
    cell.titLable.text = [dataArr[indexPath.row] objectForKey:@"consignee"];
    cell.phoneLable.text = [dataArr[indexPath.row] objectForKey:@"phone"];
    cell.addressLable.text = [[dataArr[indexPath.row] objectForKey:@"region"] stringByAppendingString:[dataArr[indexPath.row] objectForKey:@"information"]];
    cell.status = [dataArr[indexPath.row] objectForKey:@"status"];
    
    if ([[NSString stringWithFormat:@"%@",cell.status ] isEqualToString:@"1"]) {
        
        cell.selectImageView.image=[UIImage imageNamed:@"duihao"];
        cell.setLable.textColor=[UIColor blackColor];
        cell.selectBtn.selected = YES;
    }else{
        
        cell.selectImageView.image=[UIImage imageNamed:@"circile_b"];
        cell.setLable.textColor=[ZJCModel colorWithString:@"cccccc"];
        cell.selectBtn.selected = NO;
    }
    
    return cell;
}


@end
